package com.example;

import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: hanko
 * @Date: 2021-9-22 19:24
 */
@Component
@RequiredArgsConstructor
public class RedissonLock {

    private final RedissonClient redissonClient;

    public boolean lock() {
        long threadId = Thread.currentThread().getId();
        System.out.println("线程：" + threadId + "启动");
        String key = "order_lock";
        RLock lock = redissonClient.getLock(key);

        try {
            //加锁 操作很类似Java的ReentrantLock机制
            // waitTime最多等待,leaseTime自动解锁
            boolean isLock = lock.tryLock(20, 12, TimeUnit.SECONDS);
            if (isLock) {
                System.out.println("线程：" + threadId + "获取锁");
                TimeUnit.SECONDS.sleep(10);
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            //解锁
            System.out.println("线程：" + threadId + "释放锁");
            lock.unlock();
        }
        return true;
    }
}
